package kai.rating;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class AddObject extends Activity implements OnClickListener{
	private static EditText name;
	private static ImageButton addimg;
	private static Button OK;
	private static SQLiteDatabase db;
	
	private static Bitmap bmp;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Intent intent=getIntent();
		if(intent.getAction()=="First")
		{
			return;
		}
		
		db=new DBHelper(this).getWritableDatabase();
		
		setContentView(R.layout.addobject);
		name=(EditText) findViewById(R.id.name);
		addimg=(ImageButton) findViewById(R.id.addimage);
		OK=(Button) findViewById(R.id.OK);
		
		addimg.setOnClickListener(this);
		OK.setOnClickListener(this);
	}
	@Override
	public void onBackPressed()
	{
		setResult(RESULT_OK);
		finish();
	}
	@Override
	public void onClick(View v)
	{
		if(OK==v)
		{
			int id=DBHelper.MakeObjs(db,name.getText().toString());
			if(id==-1)
				Toast.makeText(this,"Name must be unique.",Toast.LENGTH_SHORT).show();
			else
			{
				if(bmp==null)
				{
					Toast.makeText(this,"Success with no image",Toast.LENGTH_SHORT).show();
					return;
				}
				FileOutputStream out;
				try {
					out=openFileOutput(Integer.toString(id)+".png",0);
					bmp.compress(Bitmap.CompressFormat.PNG,100,out);
					out.close();
				}catch (IOException e) {
					Toast.makeText(this,"Success with no image",Toast.LENGTH_SHORT).show();
					return;
				}
				
				Toast.makeText(this,"Success!",Toast.LENGTH_SHORT).show();
			}
		}
		else if(addimg==v)
		{
			Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
			startActivityForResult(intent,0);
		}
	}
	@Override
	protected void onActivityResult(int reqcode,int resultcode,Intent data)
	{
		if(resultcode!=RESULT_OK)
			return;
		Uri uri=data.getData();
		Bitmap src;
		try {
			src=Images.Media.getBitmap(getContentResolver(), uri);
		} catch (FileNotFoundException e){return;}
		catch (IOException e) {return;}
		bmp=Bitmap.createScaledBitmap(src,100,100,true);
		addimg.setImageBitmap(bmp);
	}
}
